﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Threading;
using oModbus.Message;

namespace oModbus.Device
{
    /// <summary>
    /// 串口传输类
    /// </summary>
    public class SerialTransmission : ITransmission
    {
        public event Action<byte[]> ReceivedMessageEvent;
        //public event Action<byte[]> WriteMessageEvent;
        /// <summary>
        /// 串口
        /// </summary>
        private SerialPort _sp;

        public SerialTransmission(SerialPort serialPort)
        {
            _sp = serialPort;
            //SP_Open(serialPort);
        }

        private bool _spState;
        public bool Open()
        {
            try
            {
                _sp.DataReceived += SP_DataReceived;
                _sp.Open();
                _spState = true;
                //消息发送处理线程
                var sendHandleThread = new Thread(SendHandle)
                {
                    IsBackground = true
                };

                sendHandleThread.Start();//开启线程
                //Task.Run(() =>
                //{
                //    SendHandle(); 

                //});
                return true;
            }
            catch (Exception)
            {
                // ignored
            }
            return false;
        }
        
        public bool Send(AbstractModbusMessage message)
        {
            return Send(message.PackingMessage());
        }

        /// <summary>
        /// 串口关闭
        /// </summary> 
        public void Close()
        {
            _spState = false;
            _sp.Close();
        }

   

        /// <summary>
        /// 向串口发送
        /// </summary>
        /// <param name="buffer"></param>
        private void SendSerialPort(byte[] buffer)
        {
            //申请
            _stoping.WaitOne();
            _sp.Write(buffer, 0, buffer.Length);
            //WriteMessageEvent?.Invoke(buffer);
            //释放 
            _stoping.ReleaseMutex();
        }

        public bool Send(byte[] buffer)
        {
            _commandArra.AddLast(buffer);
            return true;
        }

        /// <summary>
        /// 发送消息集合
        /// </summary>
        private readonly LinkedList<byte[]> _commandArra = new LinkedList<byte[]>();

        /// <summary>
        /// 发送数据
        /// </summary>
        protected void SendHandle()
        {
            try
            {
                while (_spState)
                {
                    if (_commandArra.Count > 0)
                    {
                        byte[] buffer = _commandArra.FirstOrDefault();
                        SendSerialPort(buffer);
                        _commandArra.RemoveFirst();
                    }
                    //暂停一会儿
                    Thread.Sleep(200);
                }
            }
            catch (Exception)
            {
                // ignored
            }
        }


        /// <summary>
        /// 串口占用标志位
        /// </summary>
        private readonly Mutex _stoping = new Mutex();
        /// <summary>
        /// 接受
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SP_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //申请
            _stoping.WaitOne();
            Thread.Sleep(100);
            int n = _sp.BytesToRead;
            var buffer = new byte[n];
            _sp.Read(buffer, 0, n);
            ReceivedMessageEvent?.Invoke(buffer);
            //释放 
            _stoping.ReleaseMutex();
        }



    }
}
